package com.yitao.cms.utils;

import com.luciad.imageio.webp.WebPReadParam;
import com.skipper.base.bean.CommonStatus;
import com.skipper.base.bean.DataOutput;
import com.skipper.base.json.JSONObject;
import com.skipper.base.utils.HttpUtils;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.FileImageInputStream;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.UUID;

/**
 * 图片上传
 *
 * @Author: Tqq
 * @Date: 2018/11/29 10:04
 */
@Component
public class UpdateFileUtils {
    @Value("${fastdfs.url}")
    private String FASTDFS_URL;
    @Value("${fastdfs.head}")
    private String PICTURE_URL_HEAD;
    @Value("${imgUrlPath}")
    private String path;

    private DataOutput updateFile(MultipartFile file, String url, String headUrl) throws IOException {
        HashMap<String, File> hashMap = new HashMap<>();
        // 获取文件后缀
        String prefix = ImageTypeUtils.getPicType2(file.getInputStream());
        if (prefix.equals(ImageTypeUtils.TYPE_UNKNOWN)){
            return new DataOutput(CommonStatus.BAD_REQUEST.getCode(),"不支持的图片格式!");
        }
        //用uuid作为文件名，防止生成的临时文件重复
        File excelFile = File.createTempFile(UUID.randomUUID().toString(), prefix);
        file.transferTo(excelFile);
        if (prefix.equals(".webp")) {//图片转化
            File file1 = new File(path);
            if (!file1.exists()) {
                file1.mkdirs();
            }
            ImageReader reader = ImageIO.getImageReadersByMIMEType("image/webp").next();
            WebPReadParam readParam = new WebPReadParam();
            readParam.setBypassFiltering(true);
            reader.setInput(new FileImageInputStream(excelFile));
            String imageUrl = path + UUID.randomUUID() + ".png";
            BufferedImage image = reader.read(0, readParam);
            ImageIO.write(image, "png", new File(imageUrl));
            excelFile = new File(imageUrl);
        }
        hashMap.put("file", excelFile);
        String post = HttpUtils.upload(url, null, null, hashMap);
        DataOutput dataOutputDto = JacksonUtils.fromJson(post, DataOutput.class);
        if (!CommonStatus.SUCCESS.getCode().equals(dataOutputDto.getStatus())) {
            throw new RuntimeException("上传图片失败");
        }
        this.removeDir();
        String s = dataOutputDto.getData().toString();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("imgUrl", s);
        dataOutputDto.setData(jsonObject);
        return dataOutputDto;
    }

    public DataOutput getHead() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("pictureUrlHead", PICTURE_URL_HEAD);
        return new DataOutput(jsonObject);
    }

    public DataOutput updateFile(MultipartFile file) throws IOException {
        return updateFile(file, FASTDFS_URL, PICTURE_URL_HEAD);
    }

    /**
     * 删除指定目录下所有文件
     */
    public void removeDir() {
        try {
            /*String path = "D:\\image";*/
            File dir = new File(path);
            String[] tempList = dir.list();
            if (tempList != null && tempList.length > 0) {
                File temp = null;
                for (int i = 0; i < tempList.length; i++) {
                    if (path.endsWith(File.separator)) {
                        temp = new File(path + tempList[i]);
                    } else {
                        temp = new File(path + File.separator + tempList[i]);
                    }
                    if (temp.isFile()) {
                        temp.delete();
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /***
     * 删除指定文件夹下所有文件
     *
     * @param filePath 文件夹完整绝对路径
     * @return
     */
    public static boolean delAllFile(String filePath) {
        boolean flag = false;
        File file = new File(filePath);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (filePath.endsWith(File.separator)) {
                temp = new File(filePath + tempList[i]);
            } else {
                temp = new File(filePath + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(filePath + "/" + tempList[i]);// 先删除文件夹里面的文件
                delFolder(filePath + "/" + tempList[i]);// 再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }

    /***
     * 删除文件夹
     *
     * @param folderPath 文件夹完整绝对路径
     */
    public  static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); // 删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            java.io.File myFilePath = new java.io.File(filePath);
            myFilePath.delete(); // 删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public  DataOutput updateRuHuaFile(String url){
        File file = new File(url);
        try {
            FileInputStream fileInputStream = new FileInputStream(url);
            MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(),
                    ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
            DataOutput dataOutput =  updateFile(multipartFile,FASTDFS_URL,PICTURE_URL_HEAD);
            //上传成功后删除文件
//            if(dataOutput.getStatus().equals(CommonStatus.SUCCESS.getCode())){
//                file.delete();
//            }
            return dataOutput;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new DataOutput(CommonStatus.SERVER_ERROR);
    }

}
